import { saveDynamicForm } from '@/api/formConfig';
// import { changeValueKey } from '@/utils/commonMethods';
// import { uploadMulti } from '@/api/file';
import commonnFunction from '@/views/commonPropertypage/commonnFunction/index.js';
// import { getByUserAndTableId } from '@/api/commonPropertypage/index';
import _ from 'lodash';
import { ExistInvoice, uploadInvoice } from '@/api/quotaInvoice/index.js';
import { addPhysicalTable, updDataPhysicalTable } from '@/api/dynamicInterface';
// 添加,编辑,查看
const showDialogForFormRuselt = [1, 3, 20];
export default {
  data() {
    return {
      showDialogForFormRuselt,
      form: {}
    };
  },
  props: {
    tableId: {
      type: Number,
      default: 0
    }
  },

  created() {
    // this.formHeaderDataInit();
  },

  // provide() {
  //   return {
  //     form: () => this.form
  //   };
  // },

  inject: ['sourceData'],

  methods: {
    propertySubData(arr, key, value) {
      // 没什么用处
      arr.bodyData.forEach(item => {
        item.data.forEach(item1 => {
          item1[key] = value;
        });
      });
    },

    tapsSubmit() {
      const submit = this.$refs.commonComponents.commonDo;
      if (submit) {
        submit('cqc-addForm', '提交').then(res => {
          const {
            data: data1,
            file: files,
            success,
            message
            // parentHeaders
          } = res;
          let flag = true;
          if (!success) {
            flag = false;
          }

          if (!data1.length) {
            flag = false;
          }

          if (flag) {
            const requestInfo = this.getRequestDataInfo();
            const { tableType, menuId, sItem } = requestInfo;

            const collectDatas = data1.reduce((prev, next) => {
              next.data.forEach(item => {
                if (!('option' in item)) {
                  item.option = 'create';
                }

                if (this.isCreate) {
                  item.option = 'create';
                }
              });

              prev.push({
                tableId: next.tableId,
                data: next.data
              });
              return prev;
            }, []);

            const requestData = {
              menuId,
              tableType,
              bodyData: collectDatas
            };

            // requestData.parentHeaders

            if (this.isCreate) {
              this.sendRequest(requestData).then(({ flag, res }) => {
                if (flag) {
                  if (files.length) {
                    this.uploadMultiFile(
                      { files, guid: res.data.formGuid },
                      requestData
                    );
                  } else {
                    this.successClose();
                  }
                }
              });
            } else if (this.isEdit) {
              requestData.menuId = undefined;
              requestData.formGuid = sItem.FORMGUID;
              this.sendRequest(requestData).then(({ flag, res }) => {
                if (flag) {
                  if (files.length) {
                    this.uploadMultiFile(
                      { files, guid: res.data.formGuid },
                      requestData
                    );
                  } else {
                    this.successClose();
                  }
                }
              });
            }
          } else {
            this.$message.warning(message);
          }
        });
      } else {
        console.warn('tab-taps submit function is not defined');
      }
    },

    uploadMultiFile({ files, guid }, requestData) {
      const { fileUpload } = commonnFunction;
      const fileUploadArr = [];
      files.forEach(async item => {
        if (
          item.file.length &&
          !Object.keys(item.file[0]).includes('voiceObj')
        ) {
          const obj = {
            files: item.file,
            guid,
            description: item.description
          };

          const additionData = {
            formRequestData: requestData,
            additionParams: {}
          };

          const bodyData = requestData.bodyData;

          if (bodyData && bodyData.length) {
            const arr = ['PROGRAMNAME2', 'PROGRAMCODE2'];
            const dataRow = bodyData[0].data[0];
            Object.keys(dataRow).forEach(key => {
              if (arr.includes(key)) {
                additionData.additionParams[key] = Reflect.get(dataRow, key);
              }
            });
          }
          fileUploadArr.push(fileUpload(obj, additionData));
        } else if (
          item.file.length &&
          Object.keys(item.file[0]).includes('voiceObj')
        ) {
          // 发票上传
          const voiceData = new FormData();
          item.file.forEach(it => {
            voiceData.append('files', it.file);
          });
          voiceData.append('tableId', item.description);
          voiceData.append('formGuid', guid);
          voiceData.append('type', item.file[0].type);
          await uploadInvoice(voiceData).then(res => {
            if (res.success) {
              this.$message({
                message: res.message,
                type: 'success'
              });
            } else {
              this.$message({
                message: res.message,
                type: 'warning'
              });
            }
          });
        }
      });
      Promise.all(fileUploadArr).then(res => {
        const resFalse = res.some(item => !item.success);
        if (!resFalse) {
          this.successClose();
        } else {
          const resData = res.find(item => !item.success);
          this.$message.warning(resData.message);
        }
        return Promise.resolve(res);
      });
      // const requestForm = new FormData();
      // requestForm.append('guid', guid);

      // files.map(file => {
      //   requestForm.append('files', file.file);
      // });
      // return uploadMulti(requestForm).then(res => {
      //   if (res.success) {
      //     this.successClose();
      //   } else {
      //     this.$message.warning(res.message);
      //   }
      //   return Promise.resolve(res);
      // });
    },

    // 上传成功后收尾
    successClose() {
      this.clearData();
      this.close();
      this.sendRequestForRefresh();
    },

    // 请求的一些参数
    getRequestDataInfo() {
      const sourceData = _.cloneDeep(this.getSourceData);
      const {
        checkbox,
        radioSelectRow: radioSelectItem,
        styleHead: { lineSelect }
      } = sourceData.form[sourceData.tableId];
      const sItem = lineSelect === 1 ? radioSelectItem : checkbox[0]; // 1单选表格 2 多选表格
      const subTableId =
        this.chooseComponents === 1 // 按钮绑定了菜单取按钮上面id 否则取选中行的id
          ? sItem && sItem['TABLEID']
          : this.clickBtnItemNow.tableId;
      return {
        sourceData,
        tableId: subTableId,
        menuId: this.$route.query.menuId,
        tableType: sourceData.tableType,
        btnItem: this.clickBtnItemNow,
        sItem
      };
    },

    submit() {
      const { isCreate, isEdit, tableId, chooseComponents, menuType } = this;
      if (menuType === 10) {
        // 物理表单
        this.physicsFrom();
        return;
      }
      if (chooseComponents === 0) {
        // tap-tabs
        return this.tapsSubmit();
      }

      const collectData = _.cloneDeep(this.formInstance().submit());

      const {
        tableId: subTableId,
        sItem,
        sourceData
      } = this.getRequestDataInfo();
      const requestData = {
        bodyData: [
          {
            tableId: subTableId,
            data: [
              {
                ...collectData,
                tableId: subTableId,
                rowNum: sItem && sItem.ROW_NUM // 目前表行无行数
              }
            ]
          }
        ]
      };
      // 是否有formGuid
      const flag = sItem && (sItem.formGuid || sItem.FORMGUID);
      if (isCreate || !flag) {
        // 走添加
        requestData.menuId = sourceData.menuId;
        this.propertySubData(requestData, 'option', 'create');
        requestData.bodyData.forEach(item => {
          item.tableId = tableId;
        });
      }

      if (isEdit && flag) {
        // 走编辑
        this.propertySubData(requestData, 'option', 'update');

        requestData.formGuid = sItem.formGuid || sItem.FORMGUID;
      }
      this.sendRequest(requestData).then(({ flag }) => {
        if (flag) {
          // const { form, tableId } = this;
          setTimeout(() => {
            this.successClose();
          }, 500);
        }
      });
    },

    // 请求主页面数据
    sendRequestForRefresh() {
      this.$parent.getQueryBodyByProduce({
        tableId: this.tableId,
        ...this.renderKey.form.searchBodyParams
      });
    },

    // (新增)
    async sendRequest(data) {
      let dataFlag = true;
      // 发票校验
      for (let i = 0; i < data.bodyData.length; i++) {
        const item = data.bodyData[i];
        if (Object.keys(item.data[0]).includes('voiceObj')) {
          const arrSet = [];
          const CodeArr = [];

          item.data.forEach(its => {
            arrSet.push(its.voiceObj.InvoiceNum);
            CodeArr.push({
              invoiceCode: its.voiceObj.InvoiceCode,
              invoiceNum: its.voiceObj.InvoiceNum
            });
          });
          if (arrSet.length === [...new Set(arrSet)].length) {
            await ExistInvoice(CodeArr).then(resJiao => {
              if (resJiao.success) {
                if (resJiao.data.result) {
                  this.$message.warning(resJiao.data.errorMessage);
                  dataFlag = false;
                }
              } else {
                this.$message.warning('校验失败');
                dataFlag = false;
              }
            });
          } else {
            this.$message.warning('上传发票不能相同');
            dataFlag = false;
          }
        }
      }
      if (dataFlag) {
        return saveDynamicForm(data).then(res => {
          this.$message[res.success ? 'success' : 'warning'](res.message);

          return Promise.resolve({
            flag: res.success,
            msg: res.message,
            res
          });
        });
      }
    },

    formInstance() {
      return this.$refs.form;
    },

    clearData() {
      this.formInstance() && this.formInstance().clearData();
    },

    // 保存的时候转换
    // changeValueKey(option, select, value) {
    //   const { renderKey, renderValue } = option;
    //   const findValueObj = select.find(item => item[renderValue] === value);
    //   // let findValue;
    //   // findValueObj ? (findValue = findValueObj[renderKey]) : value;
    //   const findValue = findValueObj ? findValueObj[renderKey] : value;
    //   return findValue;
    // },

    physicsFrom() {
      const { isCreate, isEdit, tableId } = this;
      const { headers, tabInfo } = this.renderKey.form;
      // 日期组件
      const dateSymbol = [
        'yearDateSelect',
        'monthDateSelect',
        'dayDateSelect',
        'monthDateSelectRange',
        'dayDateSelectRange'
      ];
      const request = {
        tableId
      };
      // 添加
      if (isCreate) {
        request.dataList = this.getList(headers, dateSymbol);
        addPhysicalTable(request).then(res => {
          const { success, message } = res;
          if (success) {
            this.$message.success(message);
            this.successClose();
          } else {
            this.$message.error(message);
          }
        });
        // 编辑
      } else if (isEdit) {
        const sourceData = _.cloneDeep(this.getSourceData);
        const {
          checkbox,
          radioSelectRow: radioSelectItem,
          styleHead: { lineSelect }
        } = sourceData.form[sourceData.tableId];
        const sItem = lineSelect === 1 ? radioSelectItem : checkbox[0]; // 1单选表格 2 多选表格
        // 获取编辑后的的dataList
        const editHeaders = [];
        headers.forEach(item => {
          const { dataIndex, myValue } = item;
          if (sItem[dataIndex] !== myValue) {
            editHeaders.push(item);
          }
        });

        request.dataList = this.getList(editHeaders, dateSymbol);
        if (request.dataList.length) {
          // 获取fileterList
          const filterList = [];
          const physicalTableKey = tabInfo.physicalTableKey && JSON.parse(tabInfo.physicalTableKey);
          const physicalTableKeyList = [];
          physicalTableKey.forEach(i => {
            physicalTableKeyList.push({
              dataIndex: i,
              value: sItem[i]
            });
          });
          physicalTableKeyList.forEach(i => {
            const { dataIndex, value } = i;
            filterList.push({
              col: dataIndex,
              symbol: value === '' ? '' : 'eq',
              value
            });
          });
          // physicalTableKeyList.forEach(i => {
          //   const {
          //     componentType,
          //     dataIndex,
          //     columnSelectOptions,
          //     selectViewOptions
          //   } = i;
          //   // 日期symblo为eq_d
          //   if (dateSymbol.includes(componentType)) {
          //     filterList.push({
          //       col: dataIndex,
          //       symbol: 'eq_d',
          //       value: sItem[dataIndex]
          //     });
          //     // 有选项要转换
          //   } else if (
          //     columnSelectOptions.length &&
          //     selectViewOptions &&
          //     Object.keys(selectViewOptions).length &&
          //     sItem[dataIndex]
          //   ) {
          //     const value = this.changeValueKey(
          //       selectViewOptions,
          //       columnSelectOptions,
          //       sItem[dataIndex]
          //     );
          //     filterList.push({
          //       col: dataIndex,
          //       symbol: 'eq',
          //       value
          //     });
          //   } else {
          //     filterList.push({
          //       col: dataIndex,
          //       symbol: 'eq',
          //       value: sItem[dataIndex]
          //     });
          //   }
          // });
          request.filterList = filterList;
          updDataPhysicalTable(request).then(res => {
            const { success, message } = res;
            if (success) {
              this.$message.success(message);
              this.successClose();
            } else {
              this.$message.error(message);
            }
          });
        } else {
          this.successClose();
        }
      }
    },

    getList(array, dateSymbol) {
      const arr = [];
      array.forEach(i => {
        const {
          componentType,
          dataIndex,
          myValue
        } = i;
        // 是否为日期格式
        if (dateSymbol.includes(componentType)) {
          arr.push({
            col: dataIndex,
            symbol: 'eq_d',
            value: myValue
          });
        } else {
          // const value = changeValueKey(i, myValue);
          arr.push({
            col: dataIndex,
            symbol: 'eq',
            value: myValue
          });
        }
        //  else if (
        //   // 有选项要转换
        //   columnSelectOptions.length &&
        //   selectViewOptions &&
        //   Object.keys(selectViewOptions).length &&
        //   myValue
        // ) {
        //   const value = this.changeValueKey(
        //     selectViewOptions,
        //     columnSelectOptions,
        //     myValue
        //   );
        //   arr.push({
        //     col: dataIndex,
        //     symbol: 'eq',
        //     value
        //   });
        // } else {
        //   arr.push({
        //     col: dataIndex,
        //     symbol: 'eq',
        //     value: myValue
        //   });
        // }
      });
      return arr;
    }
  },

  computed: {
    isShowCommonForm() {
      return showDialogForFormRuselt.includes(this.renderKey.buttonCode);
    },

    isCreate() {
      // 添加
      return this.renderKey.buttonCode === 1;
    },

    isEdit() {
      // 编辑
      return this.renderKey.buttonCode === 3;
    },
    // 查看
    isLook() {
      // 编辑
      return this.renderKey.buttonCode === 20;
    },

    flag() {
      // 1不可编辑,[0,2]可编辑
      return this.renderKey.buttonCode === 20 ? '1' : '0';
    },

    getSourceData() {
      return this.sourceData();
    },

    /**
     *
     *
     * @return {* } -1 无值; 0 装载 tap-tabs 的dialog; 1 form;
     *
     */
    chooseComponents() {
      const btn = this.clickBtnItemNow;
      if (Object.keys(btn).length) {
        const {
          buttonCode,
          component
          // isProcess 能进入弹窗即表示这玩意儿值为 0
        } = btn;

        if (btn.isBind === 0) {
          // 没有绑定菜单
          return 1;
        }
        // 添加
        if (buttonCode === 1) {
          if (component) {
            return 0;
          } else {
            return 1;
          }
          // 编辑
        } else if (buttonCode === 3) {
          if (component) {
            return 0;
          } else {
            return 1;
          }
        } else if (buttonCode === 20) {
          if (component) {
            return 0;
          } else {
            return 1;
          }
        } else {
          return -1;
        }
      } else {
        // 没有表示是查看且显示表头
        return 1;
      }
    }
  },

  watch: {
    isShow: {
      handler: function(v) {
        if (v && this.isShowCommonForm) {
          this.$nextTick(() => {
            // this.formHeaderDataInit();
            setTimeout(() => {
              this.formInstance() && this.formInstance().init();
            }, 200);
          });
        }
      }
    }
  }
};
